{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import PIL.Image as image\n",
    "from sklearn import preprocessing\n",
    "from sklearn.cluster import KMeans\n",
    "from skimage import color\n",
    "import matplotlib.image as mpimg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_data(filePath):\n",
    "    # 读文件\n",
    "    f = open(filePath, 'rb')\n",
    "    data = []\n",
    "    # 得到图像像素值\n",
    "    img = image.open(f)\n",
    "    # 得到图像尺寸\n",
    "    width, height = img.size\n",
    "    for x in range(width):\n",
    "        for y in range(height):\n",
    "            # 得到x，y的三个通道值\n",
    "            R, G, B = img.getpixel((x, y))\n",
    "            data.append([R, G, B])\n",
    "    f.close()\n",
    "    # 采用Min-Max规范化\n",
    "    mm = preprocessing.MinMaxScaler()\n",
    "    data = mm.fit_transform(data)\n",
    "    return np.mat(data), width, height"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 加载图像，得到规范化的结果 img，以及图像尺寸\n",
    "img, width, height = load_data('./weixin.jpg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 用K-Means对图像进行2聚类\n",
    "kmeans = KMeans(n_clusters=2)\n",
    "kmeans.fit(img)\n",
    "label = kmeans.predict(img)\n",
    "# 将图像聚类结果，转化成图像尺寸矩阵\n",
    "label = label.reshape([width, height])\n",
    "# 创建个新图像，用来保存图像聚类的结果，并设置不同的灰度值\n",
    "pic_mark = image.new('L', (width, height))\n",
    "for x in range(width):\n",
    "    for y in range(height):\n",
    "        # 根据类别设置灰度，类别0灰度为255，类别1灰度为127\n",
    "        pic_mark.putpixel((x, y), int(256/(label[x][y]+1))-1)\n",
    "pic_mark.save('weixin_mark.jpg', 'JPEG')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 分割成16个部分\n",
    "kmeans = KMeans(n_clusters=16)\n",
    "kmeans.fit(img)\n",
    "label = kmeans.predict(img)\n",
    "label = label.reshape([width, height])\n",
    "label_color = (color.label2rgb(label)*255).astype(np.uint8)\n",
    "label_color = label_color.transpose(1, 0, 2) # 1,2维调换\n",
    "images = image.fromarray(label_color)\n",
    "images.save('weixin_mark_color.jpg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建个新图像，用来保存图像聚类压缩后的结果\n",
    "img = image.new('RGB', (width, height))\n",
    "for x in range(width):\n",
    "    for y in range(height):\n",
    "        R = kmeans.cluster_centers_[label[x, y], 0]\n",
    "        G = kmeans.cluster_centers_[label[x, y], 1]\n",
    "        B = kmeans.cluster_centers_[label[x, y], 2]\n",
    "        img.putpixel((x, y), (int(R*256)-1, int(G*256)-1, int(B*256)-1))\n",
    "img.save('weixin_new.jpg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
